package org.jsola.hr.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.jsola.contract.dto.PhoneStatusDTO;
import org.jsola.contract.service.ISynchronizeContractService;
import org.jsola.hr.entity.EmpInfoDO;
import org.jsola.hr.service.IEmpInfoService;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zhenghua
 */
@Slf4j
@Service("hrSynchronizeContractServiceImpl")
public class SynchronizeContractServiceImpl implements ISynchronizeContractService {

    @Autowired
    private IEmpInfoService empInfoService;

    @Override
    public void synchronizeContractStatusByPhone(List<PhoneStatusDTO> phoneStatusDTOList, String subjectId, TokenUser tokenUser) {

        if (CollectionUtils.isEmpty(phoneStatusDTOList)) {
            return;
        }
        Map<String, Integer> phoneStatusMap = phoneStatusDTOList.parallelStream()
                .collect(Collectors.toMap(PhoneStatusDTO::getPhone, PhoneStatusDTO::getStatus));
        List<EmpInfoDO> empInfoDOList = empInfoService.selectByPhonesAndCompanyId(new ArrayList<>(phoneStatusMap.keySet()), subjectId, tokenUser.getSiteId());
        empInfoDOList.forEach(empInfoDO -> {
            EmpInfoDO updateEmpInfoDO = new EmpInfoDO();
            updateEmpInfoDO.setId(empInfoDO.getId());
            Integer contractsStatus = null == phoneStatusMap.get(empInfoDO.getPhone())
                    ? 0 : phoneStatusMap.get(empInfoDO.getPhone());
            updateEmpInfoDO.setContractsStatus(contractsStatus);
            log.info("删除合同 更新员工合同状态，员工Id：{}，手机号：{}，合同状态：{}", empInfoDO.getId(), empInfoDO.getPhone(), contractsStatus);
            empInfoService.updateByIdSelective(updateEmpInfoDO, tokenUser.getSiteId(), tokenUser.getUserId());
        });

    }
}
